#!/bin/bash

DB_USER=${DB_USER:-root}
DB_PASS=${DB_PASS:-root}

MYSQL_NEW=true

#
#  MySQL setup
#
firstrun_mysql() {

	# First install mysql
	if [[ ! -d ${DATA_DIR}/mysql ]]; then
	    echo "===> MySQL not install..."

        echo "===> Initializing maria database... "
	   	mysql_install_db --user=mysql --ldata=${DATA_DIR}
        echo "===> System databases initialized..."

	   	# Start mysql
        /usr/bin/mysqld_safe --user mysql > /dev/null 2>&1 &

        echo "===> Waiting for MySQL to start..."

		STA=1
		while [[ STA -ne 0 ]]; do
            printf "."
			sleep 5
			mysql -uroot -e "status" > /dev/null 2>&1
			STA=$?
		done
        echo "===> Start OK..."

		# 1. Create a localhost-only admin account
		mysql -u root -e "CREATE USER '$DB_USER'@'%' IDENTIFIED BY '$DB_PASS'"
		mysql -u root -e "CREATE USER '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS'"
		mysql -u root -e "CREATE USER '$DB_USER'@'127.0.0.1' IDENTIFIED BY '$DB_PASS'"
		mysql -u root -e "GRANT ALL PRIVILEGES ON *.* TO '$DB_USER'@'%' WITH GRANT OPTION"
        echo "===> Create localhost completed..."

		# shutdown mysql to wait for supervisor
		mysqladmin -u root shutdown

	else
        if [[ -e ${DATA_DIR}/mysql.sock ]]; then
            rm -f ${DATA_DIR}/mysql.sock
        fi

        MYSQL_NEW=false

	   	echo "===> Using an existing volume of MySQL"
	fi
}

firstrun_mysql
